package com.carrent.demo.Filter;


import com.alibaba.fastjson.JSON;
import com.carrent.demo.Utils.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
        AntPathMatcher matcher =new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest  request= (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String[] urls = new String[]
        {
                "/employee/login/**",
                "/employee/logout/**",
                "/backend/**",
             //   "/front/**",
             //   "/common/**",
                "/static/**",
        };

        String url = request.getRequestURI();
        final Boolean check = check(url, urls);
        if (check)
        {
            filterChain.doFilter(request,response);
            return;
        }

        if (request.getSession().getAttribute("employee")!=null)
        {
            filterChain.doFilter(request,response);
            return;
        }
        if(request.getSession().getAttribute("users")!=null)
        {
            filterChain.doFilter(request,response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    Boolean check(String url,String[] urls)
    {
        for(String s : urls)
        {

            final boolean match = matcher.match(s,url);
            if (match) return  true;
        }
        return  false;
    }
}
